package cn.easyplatform.studio.cmd.link;

import cn.easyplatform.studio.interceptor.Command;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.utils.GlobalVariableService;
import cn.easyplatform.studio.vos.LinkVo;

import java.util.Date;

public class UpdateLinkCmd extends LinkCmd implements Command<Boolean> {
    private LinkVo linkVo;
    private boolean isNewTask = false;
    public UpdateLinkCmd(LinkVo linkVo)
    {
        this.linkVo = linkVo;
    }
    //如果是新建的，则不会覆盖关系字段
    public UpdateLinkCmd(LinkVo linkVo, boolean isNewTask)
    {
        this.linkVo = linkVo;
        this.isNewTask = isNewTask;
    }
    @Override
    public Boolean execute(CommandContext cc) {
        if (linkVo == null)
            return false;
        if (isNewTask == true) {
            for (int i = 0; i < GlobalVariableService.getInstance().getDataLinkVoList().size(); i++) {
                LinkVo vo = GlobalVariableService.getInstance().getDataLinkVoList().get(i);
                if (vo.getEntityId().equals(linkVo.getEntityId())) {
                    linkVo.setChildrenEntityId(vo.getChildrenEntityId());
                    break;
                }
            }
        }
        linkVo.setUpdateUser(cc.getUser().getUserId());
        linkVo.setUpdateDate(new Date());
        boolean isSuccess = cc.getLink().updateLink("ep_" + cc.getProject().getId() + "_link", linkVo);
        if (isSuccess == false)
            return false;
        return updateValidation(cc);
    }

    protected Boolean updateValidation(CommandContext cc)
    {
        LinkVo updateVo = cc.getLink().getLinkWithEntityId("ep_"+cc.getProject().getId()+"_link", linkVo.getEntityId());
        if (updateVo == null)
            return false;
        //更换数据表缓存
        synchronized (GlobalVariableService.getInstance().getDataLinkVoList()) {
            //List<LinkVo> linkVos = GlobalVariableService.getInstance().getDataLinkVoList();
            //List<LinkVo> treeVoList = GlobalVariableService.getInstance().getLinkVoList();
            int index = -1;
            for (int i = 0; i < GlobalVariableService.getInstance().getDataLinkVoList().size(); i++) {
                LinkVo vo = GlobalVariableService.getInstance().getDataLinkVoList().get(i);
                if (vo.getEntityId().equals(updateVo.getEntityId())) {
                    index = i;
                    break;
                }
            }
            if (index >= 0)
            {
                GlobalVariableService.getInstance().getDataLinkVoList().set(index, updateVo);
                GlobalVariableService.getInstance().getLinkVoList().clear();
            }
            return true;
        }
    }
}
